<?php

namespace control;
/*
*销售退货单类
*/

class saleRefundOrderClass extends adIndexClass
{
    private const page = 'saleRefundOrder';
    private const table = 'sale_refund_order';
    private const tableMx = 'sale_refund_order_detail';
    private const title = '销售退货单';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'clientRefundOrderSearch':
                $tr = [
                    'orderNo'    => [
                        'name'  => '单据编号',
                        'width' => 300,
                        'sort'  => 1,
                    ],
                    'manager'    => [
                        'name'  => "销售员",
                        'width' => 300,
                    ],
                    'money'      => [
                        'name'  => '退货金额(' . static::$unit . ')',
                        'width' => 300,
                        'sort'  => 1,
                    ],
                    'recordDate' => [
                        'name'  => '单据日期',
                        'width' => 300,
                        'sort'  => 1,
                    ],
                    'state'      => [
                        'name'  => '状态',
                        'width' => 300,
                    ],
                ];
                break;
            default:
                $tr = [
                    'orderNo'     => [
                        'name'  => '单据编号',
                        'width' => 200,
                        'sort'  => 1,
                    ],
                    'companyName' => [
                        'name'  => "客户",
                        'width' => 200,
                    ],
                    'type'         => [
                        'name'  => "类型",
                        'width' => 200,
                    ],
                    'manager'     => [
                        'name'  => '销售员',
                        'width' => 200,
                    ],
//                    'money'       => [
//                        'name'  => '退货金额(' . static::$unit . ')',
//                        'width' => 200,
//                        'sort'  => 1,
//                    ],
                    'recordDate'  => [
                        'name'  => '单据日期',
                        'width' => 200,
                        'sort'  => 1,
                    ],
                    'state'       => [
                        'name'  => '状态',
                        'width' => 200,
                    ],
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function clientRefundOrderOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(["name" => "orderNo"]) . hidden(["name" => "targetId", "value" => $this->get('id')]),
                    '销售员'   => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name']),
                    "单据日期" => text(["name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~']]),
                ],
                [
                    "状态" => select(["name" => "state", 'option' => ['草稿', '待确认', '已确认']]),
                ],
            ],
        ], 1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 客户页卡
     * @return bool|string
     */
    public function clientRefundOrder(): bool|string
    {
        $html   = $this->clientRefundOrderOptions(false);
        $button = "";
        if ($this->power(self::page, "print")) {
            $button .= sprintf("<span onclick=\"batchPrint('%s', {targetId: '%s'})\" class='spanButton'>打印设置</span>\n", $this->get('cla'), $this->get('id'));
        }
        //返回
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }

    public function clientRefundOrderSearch(): bool|string
    {
        $khid = $this->post('targetId');
        //like查询数组
        $like = [
            "orderNo" => $this->post('orderNo'),//证件编号
        ];
        //全等查询数组
        $equal = [
            "state" => $this->post('state'),
            "stid"  => $this->post('stid'),
            'coid'  => self::$coid,
        ];
        $and   = " and khid = '$khid'";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
        }
        //排序
        $orderBy = $this->listSort([
            "search" => $this->post('list_sort_key') ?: 'recordDate desc,time',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => [],
        ]);
        //获取查询结果
        $where = search(["like" => $like, "=" => $equal]) . $and;
        $page  = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = [""];
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate   = [
                "box"    => ["name" => "listId", "value" => $array['id']],
                "detail" => ["title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"],
            ];
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "manager":
                        $row[] = self::findStaff($array['manager']);
                        break;
                    case "money":
                        $row[] = self::formattingFigure($array['money'], 'amount');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        $li     = $this->li([
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => ["html" => $liButton],
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
        ]);
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='refundForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(["name" => "orderNo"]),
                    "标签"     => text(["name" => "tages"]),
                    '客户名称' => clientProfileClass::kehuSelect(['title' => '']),
                ],
                [
                    '销售员'   => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name']),
                    "交货日期" => text(["name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~']]),
                    "状态"     => select(["name" => "state", 'option' => ['草稿', '待确认', '已确认']]),
                ],
            ],
        ]);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }


    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url    = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
//        if ($this->power(self::page, "edit")) {
//            $button .= "<span onclick=\"layer('orderTag','batchAddTags',{'table':'" . self::table . "','title':'" . self::title . "'})\" class='spanButton'>批量打标签</span>\n";
//        }
//        if ($this->power(self::page, "print")) {
//            $button .= " <span onclick=\"batchPrint('" . $this->get('cla') . "')\" class='spanButton'>批量打印</span>\n";
//        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = [
            "orderNo" => $this->post('orderNo'),//证件编号
        ];
        //全等查询数组
        $equal = [
            "state" => $this->post('state'),
            "stid"  => $this->post('stid'),
            "khid"  => $this->post('khid'),
            'coid'  => self::$coid,
        ];
        $and   = '';
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
        }
        if ($this->post('tages')) {
            $and     .= " and (";
            $tagsArr = explode('，', $this->post('tages'));
            foreach ($tagsArr as $index => $tag) {
                $and .= $index == 0 ? "tags like '%" . $tag . "%'" : " and tags like '%" . $tag . "%'";
            }
            $and .= ")";
        }
        //排序
        $orderBy = $this->listSort([
            "search" => $this->post('list_sort_key') ?: 'recordDate desc,time',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => [],
        ]);
        //获取查询结果
        $where = search(["like" => $like, "=" => $equal]) . $and;
        $page  = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = [
            $this->checkAll("listForm", "listId"),
        ];
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = [
                "box"    => ["name" => "listId", "value" => $array['id']],
                "edit"   => $array['state'] == '草稿' ? ["title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"] : [],
                "detail" => ["title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"],
                'print'  => ['title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"],
                'track'  => ["title" => "单据追踪", "click" => "newIframe('单据追踪','" . root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=销售退货单&id=" . $array['id'] . "')"],
            ];
            if ($array['state'] == '已确认') {
                unset($dominate['edit']);
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "companyName":
                        $kehu  = query('kehu', "khid = '$array[khid]'");
                        $row[] = $kehu['companyName'];
                        break;
                    case "tag":
                        $tag   = orderTagClass::getTagName($array['id']);
                        $row[] = $tag;
                        break;
                    case "manager":
                        $row[] = self::findStaff($array['manager']);
                        break;
                    case "money":
                        $row[] = self::lostZero($array['money']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalMoney = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(money),0) as money",
        ]);
        $total    = [
            'money'      => self::lostZero($totalMoney['money']),
        ];
        //生成页面
        $li = $this->li([
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => ["html" => $liButton],
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
            "total"       => $total,
        ]);
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result     = json_decode($resultJson, true);
        if ($result['warn'] == 2) {
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id   = $this->get('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");

        $button[] = [
            "name"  => "保存为草稿",
            "type"  => "点击事件",
            "title" => "保存",
            'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
        ];
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name"  => "保存并提交",
            "type"  => "点击事件",
            "title" => "保存",
            'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')",
        ];
        $result   = find(['table' => 'warehouse', 'where' => "coid = '" . self::$coid . "' and state = '启用' order by time desc"]);
        $li       = '';
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                $li .= "<li data-id='$array[id]'>{$array['name']}</li>";
            }
        }
        if (empty($li)) {
            $li = "<li>未找到仓库</li>";
        }
        $tr[]   = [
            '',
            '产品编码',
            '产品名称',
            '规格型号',
            '单位',
//            "<div class='warehouse'>仓库&emsp;<span class='del-row-button' id='chooseWareHouse'>批量</span><div class='stateBlock'><ul>{$li}</ul></div></div>",
            '数量',
//            '批次',
//            '单价(' . static::$unit . ')',
//            '未税金额（' . static::$unit . '）',
//            '税率%',
//            '税额（' . static::$unit . '）',
//            '价税合计（' . static::$unit . '）',
//            '关联订单',
        ];
        $result = find(['table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"]);
        $totalArr = ['total_num'=>0,'total_row_money'=>0,'total_tax_money'=>0,'total_money'=>0];
        foreach ($result['array'] as $k => $array) {
            $material = query('material', " id = '$array[materialId]'");
            $money    = round($array['money'] - $array['taxMoney'], 2);
            $target   = [];
            if ($array['sourceTable'] == 'sale_order_detail') {
                $targetMx = query("sale_order_detail", "id = '$array[sourceId]'");
                $target   = query('sale_order', "id = '$targetMx[orderId]'");
            } elseif ($array['sourceTable'] == 'sale_send_order_detail') {
                $targetMx = query("sale_send_order_detail", "id = '$array[sourceId]'");
                $target   = query('sale_send_order', "id = '$targetMx[orderId]'");
            }
            //$batch = selectMultiple(["name" => "batch[]", 'option' => saleSendOrderClass::getBatchArr($material['id'],$array['warehouseId']), 'title' => '请选择', 'value' => $array['batch']]);
            $batch = text(['name' => 'batch[]', 'type' => 'text', 'value' => $array['batch']]);
            $tr[]  = [
                componentClass::tablePperation($k + 1, "delTableRow(this);calculateTotal()") .
                hidden(['name' => 'mxId[]', 'value' => $array['id']]) .
                hidden(['name' => 'materialId[]', 'value' => $array['materialId']]) .
                hidden(['name' => 'sourceId[]', 'value' => $array['sourceId']]),
                $material['code'],
                $material['name'],
                $material['model'],
                select(['name' => 'unitDetail[]', 'data' => ['unit' => $array['unit']], 'change' => 'unitChange', 'option' => machiningOrderClass::unitOption($array['materialId']), 'title' => '单位', 'value' => $array['unit']]),
//                idSelect(['name' => 'warehouseId[]', 'sqlForm' => "warehouse where coid = '" . self::$coid . "' and state = '启用' order by time desc", 'sqlId' => 'id', 'sqlField' => "name", 'title' => '仓库', 'value' => $array['warehouseId']]),
                text(['name' => 'num[]', 'type' => 'text', 'blur' => 'countMoney', 'other' => self::digitalFiltering('numPrecision'), 'value' => $array['num'] ? self::lostZero($array['num'], 'numPrecision') : '']),
//                "<span class='batch'>{$batch}</span>",
//                text(['name' => 'price[]', 'type' => 'text', 'blur' => 'countMoney', 'other' => self::digitalFiltering('pricePrecision'), 'value' => $array['price'] ? self::lostZero($array['price'], 'pricePrecision') : '']),
//                "<span class='rowMoney'>{$money}</span>",
//                select(['name' => 'rate[]', 'change' => 'countMoney', 'title' => '税率', 'option' => explode('，', para('taxRate')), 'value' => $array['rate'] * 100]),
//                "<span class='taxMoney'>{$array['taxMoney']}</span>",
//                text(['name' => 'moneyWithTax[]', 'type' => 'text', 'blur' => 'calculatePrice', 'other' => self::digitalFiltering('amount'), 'value' => $array['money'] ? self::lostZero($array['money'], 'amount') : '']),
//                $target['orderNo'] ?? '',
            ];
            $totalArr['total_num'] += $array['num'];
            $totalArr['total_row_money'] += $money;
            $totalArr['total_tax_money'] += $array['taxMoney'];
            $totalArr['total_money'] += $array['money'];
        }
        $checked = $info['isTax'] ? 'checked' : '';

        $total = [
            6 => "<span id='total_num'>".self::lostZero($totalArr['total_num'])."</span>",
            9 => "<span id='total_row_money'>".self::lostZero($totalArr['total_row_money'])."</span>",
            11 => "<span id='total_tax_money'>".self::lostZero($totalArr['total_tax_money'])."</span>",
            12 => "<span id='total_money'>".self::lostZero($totalArr['total_money'])."</span>",
        ];
        $list    = $this->listTable(['tr' => $tr, 'end' => true, 'total' => $total]);

        $chooseBtn = <<<eof
<span class="smallButton" onclick="layer('{$this->get('cla')}','addMx',$('form[name=saleRefundOrderEditForm]').serialize())">选择产品</span>
eof;
        //选项控制
        $setting = optionSettingClass::getSetting('销售');
        if (isset($setting['refundWithOrder']) && $setting['refundWithOrder']) {
            $chooseBtn = '';
        }
//        $mxButton = <<<efo
//                <span class="smallButton" onclick="chooseOrder('saleSendOrder')">关联销售发货单</span>
//                <span class="smallButton" onclick="chooseOrder('saleOrder')">关联销售订单</span>
//                $chooseBtn
//                 <span style="margin-left: 20px;"><label class='checkbox'><input name='isTax' onclick="taxChange(this)" type='checkbox' $checked value='1'><span></span>&nbsp;含税</label></span>
//efo;


        $kehu     = query('kehu', "khid = '$info[khid]'");
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body           = $this->edit4([
            '基本信息' => [
                [
                    must . "客户："     => componentClass::selectText([
                            'name'      => 'khid',
                            'value'     => $info['khid'],
                            'title' => $kehu['companyName'],
                            'cla'       => 'saleOrder',
                            'fun'       => 'getClient',
                            'change'    => 'getContract',
                        ]) .
                        "<span class='del-row-button' onclick=\"newIframe('我的客户','" . root . "control/adIndex.html?cla=client&fun=edit')\" >新建</span>",
                    "合同："            =>
                        radio(array("name" => "type", 'value' => ['称差', '送不完'], "checked" => $info['type'])),
                    must . "单据日期：" => text(["name" => "recordDate", 'class' => 'text', 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                ],
                [
                    "备注：" => textarea(["name" => "text", 'class' => 'text', "value" => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '退货明细',
            'button' => $chooseBtn,
            'html' => $list,
        ]);
        $body .= $this->editBlock([
            '附件' => fileUploadClass::addFileComponent($id, '销售退货单', self::page, self::page . 'EditForm')
        ]);
        $data['html']   = $this->pageEdit([
            "html"   => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $saleOrderObj   = new saleOrderClass();
        $data['html']   .= <<<efo
<style>
.stateBlock{margin-top: 0}
.stateBlock ul li{padding: 2px 10px}
</style>
<script>
function chooseOrder(classify){
    let khid = $("[name='khid']").val();
    if (!khid){
        msg('请先选择客户','error')
        return false;
    }
    if (classify==='saleSendOrder'){
         layer('{$this->get('cla')}','addSendOrder',$('form[name=saleRefundOrderEditForm]').serialize())
    }
    if (classify==='saleOrder'){
         layer('{$this->get('cla')}','addOrder',$('form[name=saleRefundOrderEditForm]').serialize())
    }
   
}
 //点击非下拉区域隐藏
$(document).bind('click', function (e) {
    let target = $(".stateBlock");
    let obj = $(".warehouse");
    if(!target.is(e.target) && target.has(e.target).length ===0 && !obj.is(e.target) && obj.has(e.target).length ===0){
      target.hide();
    }
});
$("#chooseWareHouse").on('click',function() {
   $(".stateBlock").show();
})
$(".warehouse .stateBlock li").on('click',function() {
    let id = $(this).data('id');
    $("select[name='warehouseId[]']").val(id);
   $(".stateBlock").hide();
})
function addRow(classify = ''){
    if (classify =='saleOrder'){
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addOrderEdit',$("form[name='saleOrderForm']").serialize(),function(res) {
             $("#materialTable tbody").append(res.html);
             resetNumber($("#materialTable"))
        },'json');
    }else if (classify =='saleSendOrder'){
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addSendOrderEdit',$("form[name='saleSendOrderForm']").serialize(),function(res) {
            $("#materialTable tbody").append(res.html);
            resetNumber($("#materialTable"))
        },'json');
    }else{
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
            $("#materialTable tbody").append(res.html);
            resetNumber($("#materialTable"))
        },'json');
    }
}
//根据客户获取合同
function getContract(){
    let khid = $("[name='khid']").val();
    let val = $("[name='contractId']").val();
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getContract',{khid:khid,value:val},function(res) {
          $("#contract").html(res.html);
          $("#credits").html(res.kehu.credits);
    },'json');
}
//根据仓库获取批次
function getBatch(e){
    let warehouseId = e.value;
    let materialId = $(e).parent().parent().find("[name='materialId[]']").val();
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getBatch',{warehouseId:warehouseId,materialId:materialId},function(res) {
          $(e).parent().parent().find(".batch").html(res.batch);
    },'json');
}
</script>
efo. $saleOrderObj->editJs();
        //返回
        return $this->tab($data);
    }

    /**
     * 根据仓库获取批次
     */
    public function getBatch($warehouseId = '', $materialId = ''): bool|string
    {
        $warehouseId = $warehouseId ?: $this->post('warehouseId');
        $materialId  = $materialId ?: $this->post('materialId');
        //批号
        $json['batch'] = selectMultiple([
            "name"   => "batch[]",
            'option' => saleSendOrderClass::getBatchArr($materialId, $warehouseId),
            'title'  => '请选择',
        ]);
        return json_encode($json, 320);
    }

    /**
     * 获取合同
     */
    public function getContract()
    {
        $khid                    = $this->post('khid');
        $value                   = $this->post('value');
        $kehu                    = query('kehu', "khid = '$khid'");
        $json['kehu']['credits'] = ($kehu['credits'] ?: 0) . '/0';
        $json['html']            = selectMultiple([
            "name"     => "contractId",
            "value"    => $value,
            'table'    => "sales_contract",
            'where'    => "clientId = '$khid' and state = '已通过' order by time desc",
            'sqlId'    => 'id',
            'sqlField' => 'name',
            'title'    => '请选择',
        ]);
        return json_encode($json, 320);
    }

    public function editEdit()
    {
        $fileIdArr       = $this->post('fileId');
        $id              = $this->post('id') ?: self::getId();
        $mxIdArr         = $this->post('mxId') ?: [];
        $materialIdArr   = $this->post('materialId');
        $sourceIdArr     = $this->post('sourceId');
        $numArr          = $this->post('num');
        $batchArr        = $this->post('batch');
        $unitArr         = $this->post('unitDetail');
        $priceArr        = $this->post('price');
        $warehouseIdArr  = $this->post('warehouseId');
        $taxRateArr      = $this->post('rate');
        $moneyWithTaxArr = $this->post('moneyWithTax');
        $field           = [
            'text'       => $this->post('text'),
            'type'       => $this->post('type'),
            'contractId' => $this->post('contractId'),
            'khid'       => $this->post('khid'),
            'recordDate' => $this->post('recordDate'),
            'isTax'      => $this->post('isTax') ? 1 : 0,
        ];
        $where           = " id = '$id' ";
        $info            = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (!empty($info['id']) && $info['state'] == '已确认') {
            $json['warn'] = '此' . self::title . '已确认，不能修改';
        } else {
            $json['warn'] = '';
            if (is_array($mxIdArr) && count($mxIdArr) > 0) {
                $dataIntegration = self::dataArrangement($sourceIdArr, $numArr);  //相同订单物料数量汇总处理（便于判读）
                //判断数量是否超过销售发货单或销售单
                foreach ($mxIdArr as $k => $mxId) {
                    if (isset($sourceIdArr[$k]) && !empty($sourceIdArr[$k])) {
                        $targetInfo = query('sale_order_detail', "id = '$sourceIdArr[$k]'");
                        //已存在的退货数量
                        $num = $this->saleInRefund($id, $sourceIdArr[$k], $targetInfo['unit']);
                        if (empty($targetInfo['id'])) {
                            $targetInfo = query('sale_send_order_detail', "id = '$sourceIdArr[$k]'");
                            //已存在的退货数量
                            $num = $this->saleInRefund($id, $sourceIdArr[$k], $targetInfo['unit']);
                        }

                        $material = query('material', "id = '$targetInfo[materialId]'");
                        $orderNum = machiningOrderClass::material_num_change(
                            $targetInfo['materialId'],
                            $unitArr[$k],
                            $targetInfo['unit'],
                            $dataIntegration[$sourceIdArr[$k]]
                        );
                        if (self::formattingFigure($num + $orderNum, 'numPrecision') > $targetInfo['num']) {
                            $json['warn'] = "产品【{$material['name']}】的数量已超出可退货总数量";
                            break;
                        }
                    }
                }
            }
            if (empty($json['warn'])) {
                $kehu = query('kehu', "khid = '$field[khid]'");
                $this->startTrans();
                $isPass           = true;//事务通过标志
                $field['manager'] = $kehu['manager'];
                if (!$info['id']) {
                    $userNo       = codeTemplateClass::generateCode(self::page, [
                        'prefix' => 'XSTH' . date('Ymd', strtotime($field['recordDate'])),
                        'table'  => self::table,
                        'field'  => 'orderNo',
                        'where'  => " and coid = '" . self::$coid . "'",
                    ], $field);
                    $field        = array_merge($field, [
                        'id'      => $id,
                        'orderNo' => $userNo,
                        'state'   => '草稿',
                        'coid'    => self::$coid,
                        'stid'    => $this->control['stid'],
                    ]);
                    $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
                } else {
                    $json['warn'] = static::update([
                        "table" => self::table,
                        "field" => $field,
                        "where" => $where,
                    ]);
                }

                //添加或更新明细
                if (is_array($mxIdArr)) {
                    foreach ($mxIdArr as $k => $nid) {
                        $mx        = query(self::tableMx, "id = '$nid'");
                        $tableName = '';
                        if ($sourceIdArr[$k]) {
                            $targetInfo = query('sale_order_detail', "id = '$sourceIdArr[$k]'");
                            $tableName  = 'sale_order_detail';
                            if (empty($targetInfo['id'])) {
                                $targetInfo = query('sale_send_order_detail', "id = '$sourceIdArr[$k]'");
                                $tableName  = $targetInfo['id'] ? 'sale_send_order_detail' : '';
                            }
                        }
                        $numArr[$k]          = self::formattingFigure($numArr[$k], 'numPrecision');
                        $priceArr[$k]        = self::formattingFigure($priceArr[$k] ?? 0, 'pricePrecision');
                        $moneyWithTaxArr[$k] = self::formattingFigure($moneyWithTaxArr[$k] ?? 0, 'amount');
                        //数据格式处理
                        $taxRateArr[$k] = floatval($taxRateArr[$k] ?? 0) / 100;//税率从百分比转为小数
                        $result         = saleOrderClass::isTax($numArr[$k], $priceArr[$k], $taxRateArr[$k], $field['isTax']);
                        if (!empty($mx['id'])) {
                            //更新
                            $warn = static::update([
                                "table" => self::tableMx,
                                "field" => [
                                    'sourceId'        => $sourceIdArr[$k],
                                    'sourceTable'     => $tableName,
                                    'materialId'      => $materialIdArr[$k],
                                    'num'             => $numArr[$k],
                                    'batch'           => $batchArr[$k] ?? '',
                                    'unit'            => $unitArr[$k],
                                    'price'           => $priceArr[$k],
                                    'taxMoney'        => $result['taxMoney'],//税额
                                    'moneyWithOutTax' => $result['money'],//不含税金额
                                    'money'           => $moneyWithTaxArr[$k],//价税合计
                                    'rate'            => $taxRateArr[$k],
                                    'warehouseId'     => $warehouseIdArr[$k]?? '',
                                ],
                                "where" => " id = '$nid'",
                            ]);
                        } else {
                            //新增
                            $warn = static::insert([
                                "table" => self::tableMx,
                                "field" => [
                                    'id'              => $nid,
                                    'orderId'         => $id,
                                    'coid'            => self::$coid,
                                    'sourceId'        => $sourceIdArr[$k],
                                    'sourceTable'     => $tableName,
                                    'materialId'      => $materialIdArr[$k],
                                    'unit'            => $unitArr[$k],
                                    'num'             => $numArr[$k],
                                    'batch'           => $batchArr[$k] ?? '',
                                    'price'           => $priceArr[$k],
                                    'taxMoney'        => $result['taxMoney'],//税额
                                    'moneyWithOutTax' => $result['money'],//不含税金额
                                    'money'           => $moneyWithTaxArr[$k],//价税合计
                                    'rate'            => $taxRateArr[$k],
                                    'warehouseId'     => $warehouseIdArr[$k] ?? '',
                                ],

                            ]);
                        }
                        if (!in_array($warn, ['新增成功', '更新成功'])) {
                            $isPass       = false;
                            $json['warn'] = $warn;
                            break;
                        }
                    }
                }
                //添加主表ID到附件表
                if (is_array($fileIdArr)) {
                    $warn = update([
                        'table' => 'file',
                        'field' => ['targetId' => $id],
                        'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')",
                    ]);
                    if ($warn != '更新成功') {
                        $json['warn'] = $warn;
                        $isPass       = false;
                    }
                }
                if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
                    if ($json['warn'] == '新增成功') {
                        self::insertOperateLog($id, self::title, "新建");
                    }
                    $this->commitTrans();
                    delete(['table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"]);
                    $money = find(['table' => self::tableMx, 'single' => "orderId = '$id'", 'field' => "ifnull(sum(money),0) as total"])['total'];
                    update(['table' => self::table, 'field' => ['money' => $money], 'where' => "id = '$id'"]);
                    //添加日志
                    $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                    $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                    $this->logText(["type" => self::page, "text" => $text]);
                    //返回
                    $_SESSION['warn'] = $json['warn'];
                    $json['warn']     = 2;
                    $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
                } else {
                    $this->rollback();
                }
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 关联销售单
     * @return bool|string
     */
    public function addOrder(): bool|string
    {
        $layerId  = $this->get('cla') . ucwords($this->get('fun'));
        $formName = 'saleOrderForm';
        $html     =
            text(["name" => "orderNo", "title" => "销售订单号"]) .
            text(["name" => "recordDate", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => "单据日期"]) .
            text(["name" => "createTime", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => "交货日期"]) .
            text(["name" => "code", "title" => "产品编码"]) .
            text(["name" => "materialName", "title" => "产品名称"]) .
            text(["name" => "model", "title" => "规格型号"]) .
            hidden(['name' => 'khid', 'value' => $this->post('khid')]) .
            hidden(['name' => 'id', 'value' => $this->post('id')]) .
            hidden(['name' => 'isTax', 'value' => $this->post('isTax')]) .
            hidden(['name' => 'sourceId', 'value' => $this->post('sourceId') ? implode(',', $this->post('sourceId')) : '']);
        $button   = "<input onclick=\"addRow('saleOrder');$('#" . $layerId . "').remove()\" type='button' class='searchSub m-l-5' value='提交'>";
        $html     = $this->search($html);
        return $this->layer(["title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button]);
    }

    /**
     * 关联销售单
     * @return bool|string
     */
    public function addOrderSearch(): bool|string
    {
        //$sourceId = $this->post('sourceId') ? explode(',', $this->post('sourceId')) : []; // " and mx.id not in ('" . implode("','", $sourceId) . "')";
        $where = " so.coid='" . self::$coid . "' and so.khid = '" . $this->post('khid') . "'";
        $and   = " and so.isClose = 0";
        $like  = [
            'so.orderNo' => $this->post('orderNo'),
            'mat.code'   => $this->post('code'),
            'mat.name'   => $this->post('materialName'),
            'mat.model'  => $this->post('model'),
        ];
        $equal = [
            'so.state' => '已确认',
        ];
        if ($this->post('createTime')) {
            //交货日期
            $and .= self::timeComparison($this->post('createTime'), 'date', 'so.deliveryDate');
        }
        if ($this->post('recordDate')) {
            //单据日期
            $and .= self::timeComparison($this->post('recordDate'), 'date', 'so.recordDate');
        }
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page  = $this->page([
            "table"   => "sale_order_detail as mx join sale_order as so on mx.orderId = so.id join material as mat on mx.materialId = mat.id ",
            "field"   => "mx.id,so.orderNo,so.recordDate,so.deliveryDate,mat.code,mat.name,mat.model",
            "where"   => $where,
            'pageNum' => 50,
            "order"   => "so.recordDate desc,so.`time` desc",
        ]);
        //获取表头
        $checkAll = $this->checkAll("saleOrderForm", "saleOrderDetailId");
        $tr[]     = [$checkAll, '销售订单号', '单据日期', '交货日期', '产品编码', '产品名称', '规格型号'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = [
                "box" => ["name" => "saleOrderDetailId", "value" => $array['id']],
            ];
            $tr[]     = [
                $this->dominate($dominate),
                $array['orderNo'],
                $array['recordDate'],
                $array['deliveryDate'],
                $array['code'],
                $array['name'],
                $array['model'],
            ];
        }
        $json['html'] = $page['hint'] .
            "<form name='saleOrderForm'>" .
            hidden(['name' => 'id', 'value' => $this->post('id')]) .
            hidden(['name' => 'isTax', 'value' => $this->post('isTax')]) .
            $this->tableMany(["tr" => $tr, "showSort" => true, "page" => $page['para']]) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 已在退货单中的销售单数量
     */
    private function saleInRefund($refundOrderId, $saleOrderMxId, $toUnit): float|int
    {
        $refundNum = 0;
        $all       = find(['table' => 'sale_refund_order_detail', 'where' => "orderId !='$refundOrderId' and sourceId = '$saleOrderMxId' and coid = '" . self::$coid . "'"]);
        foreach ($all['array'] as $array) {
            $refundNum += machiningOrderClass::material_num_change($array['materialId'], $array['unit'], $toUnit, $array['num']);
        }
        return $refundNum;
    }

    /**
     * 关联销售单
     */
    public function addOrderEdit()
    {
        $id      = $this->post('id');
        $isTax   = $this->post('isTax');
        $mxIdArr = $this->post('saleOrderDetailId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择销售单';
        } else {
            $tr = [];
            foreach ($mxIdArr as $saleOrderDetailId) {
                $saleOrderMx = find([
                    'table'  => "sale_order as a join sale_order_detail as b on a.id = b.orderId",
                    'single' => " b.id = '$saleOrderDetailId' order by list asc",
                    'field'  => "b.*,a.orderNo",
                ]);
                $material    = query('material', "id = '$saleOrderMx[materialId]'");
                $select      = select([
                    'name'   => 'rate[]',
                    'change' => 'countMoney',
                    'value'  => $saleOrderMx['rate'] * 100,
                    'title'  => '税率',
                    'option' => explode('，', para('taxRate')),
                ]);
                $warehouse   = idSelect([
                    'name'     => 'warehouseId[]',
                    'sqlForm'  => "warehouse where coid = '" . self::$coid . "' and state = '启用' order by time desc",
                    'sqlId'    => 'id',
                    'sqlField' => "name",
                    'title'    => '仓库',
                ]);

                //已进入到退货单的销售单数量
                $refundNum = $this->saleInRefund($id, $saleOrderMx['id'], $saleOrderMx['unit']);
                $num       = ($saleOrderMx['num'] - $refundNum) > 0 ? self::formattingFigure($saleOrderMx['num'] - $refundNum, 'numPrecision') : 0;
                $price     = self::formattingFigure($saleOrderMx['price'], 'pricePrecision');

                $moneyRes     = saleOrderClass::isTax($num, $price, $saleOrderMx['rate'], $isTax);
                $money        = $moneyRes['money'];
                $taxMoney     = $moneyRes['taxMoney'];
                $moneyWithTax = $moneyRes['moneyWithTax'];
                $suiji        = self::getId();
                $unitSelect   = select([
                    'name'   => 'unitDetail[]',
                    'data'   => ['unit' => $saleOrderMx['unit']],
                    'change' => 'unitChange',
                    'option' => machiningOrderClass::unitOption($saleOrderMx['materialId']),
                    'title'  => '单位',
                    'value'  => $saleOrderMx['unit'],
                ]);
                //$batch = selectMultiple(["name" => "batch[]", 'option' => saleSendOrderClass::getBatchArr($material['id'],''), 'title' => '请选择', 'value' => '']);
                $batch = text(['name' => 'batch[]', 'type' => 'text', 'value' => '']);
                $tr[]  = [
                    componentClass::tablePperation('', "delTableRow(this);calculateTotal()") .
                    hidden(['name' => 'mxId[]', 'value' => $suiji]) .
                    hidden(['name' => 'materialId[]', 'value' => $saleOrderMx['materialId']]) .
                    hidden(['name' => 'sourceId[]', 'value' => $saleOrderMx['id']]),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $unitSelect,
                    $warehouse,
                    text(['name' => 'num[]', 'type' => 'text', 'blur' => 'countMoney', 'other' => self::digitalFiltering('numPrecision'), 'value' => $num]),
                    "<span class='batch'>{$batch}</span>",
                    text(['name' => 'price[]', 'type' => 'text', 'blur' => 'countMoney', 'other' => self::digitalFiltering('pricePrecision'), 'value' => $price]),
                    "<span class='rowMoney'>{$money}</span>",
                    $select,
                    "<span class='taxMoney'>{$taxMoney}</span>",
                    text(['name' => 'moneyWithTax[]', 'type' => 'text', 'blur' => 'calculatePrice', 'other' => self::digitalFiltering('amount'), 'value' => $moneyWithTax]),
                    $saleOrderMx['orderNo'],
                ];
            }
            $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 关联销售发货单
     * @return bool|string
     */
    public function addSendOrder(): bool|string
    {
        $layerId  = $this->get('cla') . ucwords($this->get('fun'));
        $formName = 'saleSendOrderForm';
        $html     =
            text(["name" => "orderNo", "title" => "销售发货单号"]) .
            text(["name" => "recordDate", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => "单据日期"]) .
            text(["name" => "code", "title" => "产品编码"]) .
            text(["name" => "materialName", "title" => "产品名称"]) .
            text(["name" => "model", "title" => "规格型号"]) .
            hidden(['name' => 'khid', 'value' => $this->post('khid')]) .
            hidden(['name' => 'id', 'value' => $this->post('id')]) .
            hidden(['name' => 'isTax', 'value' => $this->post('isTax')]) .
            hidden(['name' => 'sourceId', 'value' => $this->post('sourceId') ? implode(',', $this->post('sourceId')) : '']);
        $button   = "<input onclick=\"addRow('saleSendOrder');$('#" . $layerId . "').remove()\" type='button' class='searchSub m-l-5' value='提交'>";
        $html     = $this->search($html);
        return $this->layer(["title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button]);
    }

    /**
     * 关联销售发货单
     * @return bool|string
     */
    public function addSendOrderSearch(): bool|string
    {
        //$sourceId = $this->post('sourceId') ? explode(',', $this->post('sourceId')) : [];//" and mx.id not in ('" . implode("','", $sourceId) . "')";
        $where = " sso.coid='" . self::$coid . "' and sso.khid = '" . $this->post('khid') . "'";
        $and   = '';
        $like  = [
            'sso.orderNo' => $this->post('orderNo'),
            'mat.code'    => $this->post('code'),
            'mat.name'    => $this->post('materialName'),
            'mat.model'   => $this->post('model'),
        ];
        $equal = [
            'sso.state' => '已确认',
        ];
        if ($this->post('recordDate')) {
            //单据日期
            $and .= self::timeComparison($this->post('recordDate'), 'date', 'sso.recordDate');
        }
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page  = $this->page([
            "table"   => "sale_send_order_detail as mx join sale_send_order as sso on mx.orderId = sso.id join material as mat on mx.materialId = mat.id ",
            "field"   => "mx.id,mx.num,sso.orderNo,sso.recordDate,mat.code,mat.name,mat.model",
            "where"   => " {$where} ",
            'pageNum' => 50,
            "order"   => "sso.recordDate desc,sso.`time` desc",
        ]);
        //获取表头
        $checkAll = $this->checkAll("saleSendOrderForm", "saleSendOrderDetailId");
        $tr[]     = [$checkAll, '销售发货单号', '单据日期', '产品编码', '产品名称', '规格型号', '发货数量'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = [
                "box" => ["name" => "saleSendOrderDetailId", "value" => $array['id']],
            ];
            $tr[]     = [
                $this->dominate($dominate),
                $array['orderNo'],
                $array['recordDate'],
                $array['code'],
                $array['name'],
                $array['model'],
                self::lostZero($array['num'], 'numPrecision'),
            ];
        }
        $json['html'] = $page['hint'] .
            "<form name='saleSendOrderForm'>" .
            hidden(['name' => 'isTax', 'value' => $this->post('isTax')]) .
            hidden(['name' => 'id', 'value' => $this->post('id')]) .
            $this->tableMany(["tr" => $tr, "showSort" => true, "page" => $page['para']]) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 已在退货单中的销售发货单数量
     */
    private function sendInRefund($refundOrderId, $sendOrderMxId, $toUnit): float|int
    {
        $refundNum = 0;
        $all       = find(['table' => 'sale_refund_order_detail', 'where' => "orderId !='$refundOrderId' and sourceId = '$sendOrderMxId' and coid = '" . self::$coid . "'"]);
        foreach ($all['array'] as $array) {
            $refundNum += machiningOrderClass::material_num_change($array['materialId'], $array['unit'], $toUnit, $array['num']);
        }
        return $refundNum;
    }

    /**
     * 关联销售发货单
     */
    public function addSendOrderEdit(): bool|string
    {
        $id      = $this->post('id');
        $mxIdArr = $this->post('saleSendOrderDetailId');
        $isTax   = $this->post('isTax');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择销售发货单';
        } else {
            $tr = [];
            foreach ($mxIdArr as $saleSendOrderDetailId) {
                $saleSendOrderMx = find([
                    'table'  => "sale_send_order as a join sale_send_order_detail as b on a.id = b.orderId",
                    'single' => " b.id = '$saleSendOrderDetailId' order by list asc",
                    'field'  => "b.*,a.orderNo",
                ]);
                $material        = query('material', "id = '$saleSendOrderMx[materialId]'");
                $select          = select([
                    'name'   => 'rate[]',
                    'change' => 'countMoney',
                    'value'  => $saleSendOrderMx['rate'] * 100,
                    'title'  => '税率',
                    'option' => explode('，', para('taxRate')),
                ]);
                $warehouse       = idSelect([
                    'name'     => 'warehouseId[]',
                    'sqlForm'  => "warehouse where coid = '" . self::$coid . "' and state = '启用' order by time desc",
                    'sqlId'    => 'id',
                    'sqlField' => "name",
                    'title'    => '仓库',
                ]);
                //已进入到退货单的销售发货单数量
                $refundNum = $this->sendInRefund($id, $saleSendOrderMx['id'], $saleSendOrderMx['unit']);
                //剩余可退货的数量
                $num          = ($saleSendOrderMx['num'] - $refundNum) > 0 ? self::formattingFigure($saleSendOrderMx['num'] - $refundNum, 'numPrecision') : 0;
                $price        = self::formattingFigure($saleSendOrderMx['price'], 'pricePrecision');
                $moneyRes     = saleOrderClass::isTax($num, $price, $saleSendOrderMx['rate'], $isTax);
                $money        = $moneyRes['money'];
                $taxMoney     = $moneyRes['taxMoney'];
                $moneyWithTax = $moneyRes['moneyWithTax'];

                $suiji      = self::getId();
                $unitSelect = select([
                    'name'   => 'unitDetail[]',
                    'data'   => ['unit' => $saleSendOrderMx['unit']],
                    'change' => 'unitChange',
                    'option' => machiningOrderClass::unitOption($saleSendOrderMx['materialId']),
                    'title'  => '单位',
                    'value'  => $saleSendOrderMx['unit'],
                ]);
                //$batch = selectMultiple(["name" => "batch[]", 'option' => saleSendOrderClass::getBatchArr($material['id'],''), 'title' => '请选择', 'value' => '']);
                $batch = text(['name' => 'batch[]', 'type' => 'text', 'value' => '']);
                $tr[]  = [
                    componentClass::tablePperation('', "delTableRow(this);calculateTotal()") .
                    hidden(['name' => 'mxId[]', 'value' => $suiji]) .
                    hidden(['name' => 'materialId[]', 'value' => $saleSendOrderMx['materialId']]) .
                    hidden(['name' => 'sourceId[]', 'value' => $saleSendOrderMx['id']]),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $unitSelect,
                    $warehouse,
                    text(['name' => 'num[]', 'type' => 'text', 'blur' => 'countMoney', 'other' => self::digitalFiltering('numPrecision'), 'value' => $num]),
                    "<span class='batch'>{$batch}</span>",
                    text(['name' => 'price[]', 'type' => 'text', 'blur' => 'countMoney', 'other' => self::digitalFiltering('pricePrecision'), 'value' => $price]),
                    "<span class='rowMoney'>{$money}</span>",
                    $select,
                    "<span class='taxMoney'>{$taxMoney}</span>",
                    text(['name' => 'moneyWithTax[]', 'type' => 'text', 'blur' => 'calculatePrice', 'other' => self::digitalFiltering('amount'), 'value' => $moneyWithTax]),
                    $saleSendOrderMx['orderNo'],
                ];
            }
            $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }


    /**
     *
     * @return bool|string
     */
    public function addMx()
    {
        $layerId  = $this->get('cla') . ucwords($this->get('fun'));
        $formName = 'mxForm';
        $html     =
            materialClass::typeSelect(name: 'type') .
            text(["name" => "code", "title" => "产品编码"]) .
            text(["name" => "materialName", "title" => "产品名称"]) .
            text(["name" => "model", "title" => "规格型号"]) .
            hidden(['name' => 'contractId', 'value' => $this->post('contractId')]) .
            hidden(['name' => 'materialId', 'value' => $this->post('materialId') ? implode(',', $this->post('materialId')) : '']);
        $button   = "<input onclick=\"addRow();removeSelectedContent('" . $formName . "')\" type='button' class='searchSub m-l-5' value='继续添加'>";
        $button   .= "<input onclick=\"addRow();$('#" . $layerId . "').remove()\" type='button' class='searchSub m-l-5' value='提交'>";
        $html     = $this->search($html);
        return $this->layer(["title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button]);
    }

    /**
     *添加产品
     */
    public function addMxSearch()
    {
        $contractId = $this->post('contractId');
        /*$materialId = $this->post('materialId') ? explode(',', $this->post('materialId')) : [];
        $where = " a.id not in ('" . implode("','", $materialId) . "')";*/
        $where = "";
        if ($contractId) {
            $where .= " and a.id in (select materialId from sales_contract_detail where orderId = '$contractId' and materialId!='')";
        } else {
            $where .= " and a.coid='" . self::$coid . "' ";
        }
        $like        = [
            'a.name'          => $this->post('materialName'),
            'code'            => $this->post('code'),
            'model'           => $this->post('model'),
            'a.typeName'      => $this->post('type'),
            'a.supplyControl' => saleOrderClass::ctrlSale() ? '允许销售' : '',
        ];
        $equal       = [
            'a.state' => '启用',
        ];
        $where       .= search(["like" => $like, "=" => $equal]);
        $page        = $this->page([
            "table"   => "material as a",
            "field"   => "a.*",
            "where"   => " {$where} ",
            'pageNum' => 50,
            "order"   => "a.`time` ASC",
        ]);
        $materialObj = new materialClass();
        //获取表头
        $checkAll = $this->checkAll("mxForm", "mxId");
        $tr[]     = [$checkAll, '分类', '产品编码', '产品名称', '规格型号'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = [
                "box" => ["name" => "mxId", "value" => $array['id']],
            ];
            $checkBox = $this->dominate($dominate);
            if (!empty($contractId) && $array['coid'] != self::$coid) {
                $checkBox = "<span class='no-choose'>--</span>";
            }
            $tr[] = [
                $checkBox,
                $materialObj::getTypePath($array['typeId']),
                $array['code'],
                $array['name'],
                $array['model'],
            ];
        }
        $json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(["tr" => $tr, "showSort" => true, "page" => $page['para']]) . "</form>" . $this->js() . $page['button'];
        return json_encode($json, 320);
    }

    public function js()
    {
        return <<<efo
<script>
$(function (){
    $(".no-choose").parent().parent().css('color','#d7d7d7');
    $(".no-choose").parent().parent().attr('title','不是当前账套的产品，不可选择');
})
</script>
efo;

    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $mxIdArr = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择产品';
        } else {
            $tr = [];
            foreach ($mxIdArr as $mxId) {
                $material   = query('material', "id = '$mxId'");
                $select     = select([
                    'name'   => 'rate[]',
                    'change' => 'countMoney',
                    'title'  => '税率',
                    'option' => explode('，', para('taxRate')),
                ]);
                $id         = self::getId();
                $warehouse  = idSelect([
                    'name'     => 'warehouseId[]',
                    'sqlForm'  => "warehouse where coid = '" . self::$coid . "' and state = '启用' order by time desc",
                    'sqlId'    => 'id',
                    'sqlField' => "name",
                    'title'    => '仓库',
                ]);
                $unitSelect = select([
                    'name'   => 'unitDetail[]',
                    'data'   => ['unit' => $material['unit']],
                    'change' => 'unitChange',
                    'option' => machiningOrderClass::unitOption($material['id']),
                    'title'  => '单位',
                    'value'  => $material['unit'],
                ]);
                //$batch = selectMultiple(["name" => "batch[]", 'option' => saleSendOrderClass::getBatchArr($material['id'],''), 'title' => '请选择', 'value' => '']);
                $batch = text(['name' => 'batch[]', 'type' => 'text', 'value' => '']);
                $tr[]  = [
                    componentClass::tablePperation('', "delTableRow(this);calculateTotal()") .
                    hidden(['name' => 'mxId[]', 'value' => $id]) .
                    hidden(['name' => 'materialId[]', 'value' => $mxId]) .
                    hidden(['name' => 'sourceId[]', 'value' => '']),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $unitSelect,
//                    $warehouse,
                    text(['name' => 'num[]', 'type' => 'text', 'blur' => 'countMoney', 'other' => self::digitalFiltering('numPrecision'), 'value' => '']),
//                    "<span class='batch'>{$batch}</span>",
//                    text(['name' => 'price[]', 'type' => 'text', 'blur' => 'countMoney', 'other' => self::digitalFiltering('pricePrecision'), 'value' => '']),
//                    "<span class='rowMoney'>0</span>",
//                    $select,
//                    "<span class='taxMoney'>0</span>",
//                    text(['name' => 'moneyWithTax[]', 'type' => 'text', 'blur' => 'calculatePrice', 'other' => self::digitalFiltering('amount'), 'value' => '']),
//                    '',
                ];
            }
            $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = [
                "id" => $info['id'],
            ];

            $button = [];
            if ($info['state'] == '草稿') {
                if ($this->power(self::page, "edit")) {
                    //按钮
                    $button[] = [
                        "name"  => "提交",
                        "type"  => "弹出层",
                        "cla"   => $this->get('cla'),
                        "fun"   => "operate",
                        "post"  => ["act" => 'commit', "id" => $info['id']],
                        'style' => 'li-btn-blue-bg',
                    ];
                    //按钮
                    $button[] = [
                        "name"  => "编辑",
                        "type"  => "顶部页卡",
                        "title" => "编辑用户",
                        "url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],

                    ];
                }
                if ($this->power(self::page, "del")) {
                    //按钮
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla"  => $this->get('cla'),
                        "fun"  => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
            }
            //按钮
            $button[] = [
                "name" => "打印",
                "type" => "点击事件",
                "fun"  => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$info['id']}')",
            ];
            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name"  => "复核",
                    "type"  => "弹出层",
                    "cla"   => $this->get('cla'),
                    "fun"   => "operate",
                    "post"  => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($this->power(self::page, "confirm") && $info['state'] != '草稿') {
                $button[] = [
                    "name" => "撤回",
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],
                ];
            }
            $button[] = [
                "name"  => "单据追踪",
                "type"  => "顶部页卡",
                "title" => "单据追踪",
                "url"   => $this->root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=销售退货单&id=" . $info['id'],
            ];
            //操作记录
            $button[] = self::operateLogBut($info['id'], 1);

            $sales_contract = query('sales_contract', "id = '$info[contractId]'");
            $isTax          = $info['isTax'] ? '含税' : '不含税';
//            $tr[]           = ['产品编码', '产品名称', '规格型号', '单位', '仓库', '数量', '批次', $isTax . '单价(' . static::$unit . ')', '未税金额（' . static::$unit . '）', '税率%', '税额（' . static::$unit . '）', '价税合计（' . static::$unit . '）', '关联订单'];
            $tr[]           = ['产品编码', '产品名称', '规格型号', '单位',  '数量'];
            $result         = find(['table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"]);
            foreach ($result['array'] as $array) {
                $material = query('material', " id = '$array[materialId]'");
                $target   = [];
                if ($array['sourceTable'] == 'sale_order_detail') {
                    $targetMx = query("sale_order_detail", "id = '$array[sourceId]'");
                    $target   = query('sale_order', "id = '$targetMx[orderId]'");
                } elseif ($array['sourceTable'] == 'sale_send_order_detail') {
                    $targetMx = query("sale_send_order_detail", "id = '$array[sourceId]'");
                    $target   = query('sale_send_order', "id = '$targetMx[orderId]'");
                }

                $warehouse = query('warehouse', "id = '$array[warehouseId]'");
                $tr[]      = [
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
//                    $warehouse['name'],
                    self::lostZero($array['num'], 'numPrecision'),
//                    $array['batch'],
//                    self::lostZero($array['price'], 'pricePrecision'),
//                    self::formattingFigure($array['money'] - $array['taxMoney'], 'amount'),
//                    ($array['rate'] * 100) . '%',
//                    self::lostZero($array['taxMoney'], 'amount'),
//                    self::lostZero($array['money'], 'amount'),
//                    $target['orderNo'] ?? '',
                ];
            }
            $total               = find([
                'table'  => self::tableMx,
                'field'  => "ifnull(sum(num),0) as num,ifnull(sum(money),0) as totalMoney,ifnull(sum(taxMoney),0) as taxMoney,ifnull(sum(moneyWithOutTax),0) as money",
                'single' => "orderId = '$info[id]'",
            ]);
            $total['num']        = $total['num'] ?? 0;
            $total['totalMoney'] = $total['totalMoney'] ?? 0;
            $total['money']      = $total['money'] ?? 0;
            $total['taxMoney']   = $total['taxMoney'] ?? 0;
            $total_tr            = [
                5  => self::lostZero($total['num'], 'numPrecision'),
                8  => self::lostZero($total['money']),
                10 => self::lostZero($total['taxMoney']),
                11 => self::lostZero($total['totalMoney']),
            ];
            $kehu                = query('kehu', "khid = '$info[khid]'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html']   = $this->tableShow([
                '基本信息' => [
                    [
                        "客户"     => $kehu['companyName'],
                        "合同名称" => $sales_contract['name'],
                        "单据日期" => self::null($info['recordDate']),
                        "单据编号" => $info['orderNo'],
                    ],
                    [
                        "制单人"   => self::findStaff($info['stid']),
                        "状态"     => $info['state'],
                        '单据标签' => orderTagClass::getTagName($info['id']),
                    ],
                    [
                        "备注" => pre($info['text']),
                    ],
                ],
            ]);
            $data['html'] .= $this->detailList([
                'title' => '退货明细',
                'html' => $this->listTable(['tr' => $tr, 'showEmpty' => true, 'total' => $total_tr, 'showSort' => true]),
            ]);
            $data['html'] .= $this->detailBlock([
                '附件' => fileUploadClass::showFile($info['id'], '销售退货单')
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id    = $this->post('id');
        $info  = query(self::table, " id = '$id'");
        $field = [
            'state'       => '已确认',
            'checkId'     => self::$stid,
            'confirmTime' => $this->time,
        ];
        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此销售退货单';
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = '此退货单不是待确认状态，不能确认';
        } else {
            $this->startTrans();
            $json['warn'] = update([
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ]);
            //生成入库单
            $bool = $this->insertInventory($info);
            if ($bool !== true) {
                $json['warn'] = $bool;
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //更新订单实际交货情况
                $this->updateDeliveryDate($info);

                $this->commitTrans();
                // 单据是否需要复核
                if (!in_array(self::page, self::$publicSettings['documentReview'])) {
                    self::insertOperateLog($info['id'], self::title, "提交、复核");
                } else {
                    self::insertOperateLog($info['id'], self::title, "复核");
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 更新订单实际交货日期
     */
    private function updateDeliveryDate($info): bool|string
    {
        $result        = find(['table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"]);
        $sale_order_id = [];
        foreach ($result['array'] as $array) {
            if ($array['sourceTable'] == 'sale_order_detail') {
                $sale_order_detail = query('sale_order_detail', "id = '$array[sourceId]'", "id,orderId,num,send_num");

            } elseif ($array['sourceTable'] == 'sale_send_order_detail') {
                $sale_send_order_detail = query('sale_send_order_detail', "id = '$array[sourceId]'", "id,orderId,saleOrderMxId");
                $sale_order_detail      = query('sale_order_detail', "id = '$sale_send_order_detail[saleOrderMxId]'", "id,orderId,num,send_num");
            }
            if (isset($sale_order_detail['id']) && $sale_order_detail['id']) {
                $refundTotal = find([
                    'table'  => self::tableMx,
                    'single' => " sourceId = '$array[sourceId]' and orderId in (select id from sale_refund_order where coid = '" . self::$coid . "' and state = '已确认') ",
                    'field'  => "ifnull(sum(num),0) as num",
                ]);
                // 增加销售订单的已发货数量
                update([
                    "table" => 'sale_order_detail',
                    "field" => ['refund_num' => $refundTotal['num']],
                    "where" => "id = '$sale_order_detail[id]'",
                ]);
                if (!in_array($sale_order_detail['orderId'], $sale_order_id)) $sale_order_id[] = $sale_order_detail['orderId'];
            }
        }
        //修改主订单
        foreach ((array)$sale_order_id as $orderId) {
            $sale_order               = query('sale_order', "id = '$orderId'", "id,deliveryDate,actual_delivery_date");
            $total                    = find([
                'table'  => 'sale_order_detail',
                'single' => "orderId = '$orderId'",
                'field'  => "ifnull(sum(num),0) as num,ifnull(sum(send_num),0) as send_num,ifnull(sum(refund_num),0) as refund_num",
            ]);
            $field                    = [];
            $field['send_num']        = $total['send_num'];
            $field['refund_num']      = $total['refund_num'];
            $residue                  = $total['num'] - $total['send_num'] + $total['refund_num'];
            $field['completion_rate'] = round(($total['send_num'] - $total['refund_num']) / $total['num'], 4);

            // 是否按期交货
            if ($residue <= 0 && strtotime($this->date) <= strtotime($sale_order['deliveryDate'])) {
                $field['deliver_on_schedule'] = 1;
            } else {
                $field['deliver_on_schedule'] = 0;
            }
            if (!empty($field)) {
                update([
                    "table" => 'sale_order',
                    "field" => $field,
                    "where" => "id = '$sale_order[id]'",
                ]);
            }

        }
        return true;
    }

    /**
     * 生成入库单
     */
    private function insertInventory($info)
    {
        $re_array = [];//根据仓库重新分组
        $result   = find(['table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"]);
        foreach ($result['array'] as $array) {
            $re_array[$array['warehouseId']][] = $array['id'];
        }
        $kehu  = query('kehu', "khid = '$info[khid]'");
        $index = 1;
        foreach ($re_array as $warehouseId => $array) {
            $id     = self::getId();
            $field  = [
                'id'               => $id,
                'type'             => '销售退货',
                'coid'             => self::$coid,
                'sourceTable'      => self::table,
                'sourceId'         => $info['id'],
                'warehouseId'      => $warehouseId,
                'targetId'         => $info['khid'],
                'classify'         => 1,
                'state'            => '待入库',
                'stid'             => self::$stid,
                'orderDate'        => $this->date,
                'sourceDate'       => $info['recordDate'],
                'sourceNo'         => $info['orderNo'],
                'sourceTargetName' => $kehu['companyName'],
            ];
            $userNo = codeTemplateClass::generateCode('inStock', [
                'prefix' => 'KCRK' . date('Ymd'),
                'table'  => 'inventory',
                'field'  => 'orderNo',
                'index'  => $index,
                'where'  => " and coid = '" . self::$coid . "'",
            ], $field);
            $index++;
            $field['orderNo'] = $userNo;
            $warn             = static::insert([
                'table' => 'inventory',
                'field' => $field,
            ]);
            if ($warn != '新增成功') {
                return '生成入库单失败';
            }
            foreach ($array as $mxId) {
                $mx = query(self::tableMx, "id = '$mxId'");
                //$price = inventoryDefaultClass::pricingRules('inStockPrice', $mx['materialId']);
                $warn = static::insert([
                    'table' => 'inventory_detail',
                    'field' => [
                        'id'          => self::getId(),
                        'coid'        => self::$coid,
                        'sourceTable' => self::tableMx,
                        'sourceId'    => $mx['id'],
                        'materialId'  => $mx['materialId'],
                        'warehouseId' => $warehouseId,
                        'unit'        => $mx['unit'],
                        'orderId'     => $id,
                        'orderNum'    => $mx['num'],
                        'batch'       => $mx['batch'],
                        'rate'        => $mx['rate'],
                        'price'       => $mx['price'],
                    ],
                ]);
                if ($warn != '新增成功') {
                    return '生成入库单明细失败';
                }
            }
        }
        return true;
    }


    /**
     * 撤回
     */
    public function cancelEdit()
    {
        $id    = $this->post('id');
        $info  = query(self::table, " id = '$id'");
        $field = [
            'state'       => '草稿',
            'checkId'     => '',
            'confirmTime' => '',
        ];
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有撤回权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此销售退货单';
        } elseif ($info['state'] == '草稿') {
            $json['warn'] = '此退货单草稿状态，无需撤回';
        } elseif (static::total(['table' => 'inventory', "where" => "sourceId = '$info[id]' and coid = '" . self::$coid . "' and state in ('部分入库','已入库')"]) > 0) {
            $json['warn'] = '此退货单已存在有入库的单据，不能撤回';
        } else {
            $json['warn'] = update([
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ]);
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //删除入库单
                delete(['table' => 'inventory_detail', 'where' => "orderId in (select id from inventory where sourceId = '$info[id]' and coid = '" . self::$coid . "')"]);
                delete(['table' => 'inventory', 'where' => "sourceId = '$info[id]'"]);
                self::insertOperateLog($id, self::title, "撤回");
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * Desc : 提交前数据验证
     * User : you name
     * Date : 2023-11-17 16:04
     * @param $info
     * @return string|bool
     */
    public function dataValidation($info): string|bool
    {
        $annotation = [
            'khid'       => '客户',
            'recordDate' => '单据日期',
        ];
        $rules      = [
            'khid'       => 'required',
            'recordDate' => 'required|date',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($info, $rules)->isOk();
        if ($result === false) {
            return $vt->getErrs()[0];  // 多个规则提示最前面一条
        }
        $result = find(['table' => self::tableMx, 'field' => 'id,materialId,num,unit,price,warehouseId', 'where' => "orderId = '$info[id]' order by list"]);
        if (count($result['array']) == 0) {
            return "请完善退货明细";
        }
        if (static::is_null_array(array_column($result['array'], 'materialId'))) {
            return "退货明细中【产品】不能为空";
        }
        if (static::is_null_array(array_column($result['array'], 'unit'))) {
            return "退货明细中【单位】不能为空";
        }
//        if (static::is_null_array(array_column($result['array'], 'warehouseId'))) {
//            return "退货明细中【仓库】不能为空";
//        }
//        if (static::is_null_array(array_column($result['array'], 'price'))) {
//            return "退货明细中【单价】不能为空";
//        }
        if (static::is_null_array(array_column($result['array'], 'num'), false)) {
            return "退货明细中【数量】不能为空，且必须大于0";
        }

        return true;
    }


    /**
     * 提交
     */
    public function commitEdit()
    {
        $id    = $this->post('id');
        $info  = query(self::table, " id = '$id'");
        $field = [
            'state' => '待确认',
        ];
        //提交前数据验证
        $json['warn'] = $this->dataValidation($info);
        if ($json['warn'] !== true) {
            goto resp;
        }
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此' . self::title;
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '此' . self::title . '不是草稿状态，不能提交';
        } else {
            $this->startTrans();
            $json['warn'] = update([
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ]);
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 单据是否需要复核
                if (!in_array(self::page, self::$publicSettings['documentReview'])) {
                    $resultJson = $this->confirmEdit();
                    $json       = json_decode($resultJson, true);
                    if ($json['warn'] != 2) {
                        $this->rollback();
                        goto resp;
                    }
                } else {
                    self::insertOperateLog($info['id'], self::title, "提交");
                }
                $this->commitTrans();
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act  = $this->post('act') ?? '';
        $pwd  = $word = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'confirm':
                $act      = 'confirm';
                $msg      = '确认';
                $title    = '是否已确认此销售退货单，确认后将不可修改？';
                $function = 'confirmEdit';
                $form     = self::page . 'OperateForm, detailForm';
                $power    = '';
                $word     = true;
                break;
            case 'commit':
                $act      = 'edit';
                $msg      = '编辑';
                $title    = '是否确认提交此销售退货单？';
                $function = 'commitEdit';
                $form     = self::page . 'OperateForm, detailForm';
                $power    = '';
                $word     = true;
                break;
            case 'cancel':
                $act      = 'cancel';
                $msg      = '撤回';
                $title    = '是否确认撤回此销售退货单？';
                $function = 'cancelEdit';
                $form     = self::page . 'OperateForm, detailForm';
                $power    = '';
                $word     = true;
                break;
            default:
                $act      = 'del';
                $msg      = '删除' . self::title;
                $title    = self::page . 'Delete';
                $function = 'delete';
                $form     = self::page . 'OperateForm, listForm, quoForm';
                $power    = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "删除失败：已确认，暂不能删除";
                } else {
                    //最后删除基本参数
                    fileClass::deleteFile($id);
                    delete(["table" => self::table, "where" => " id = '$id' "]);
                    delete(["table" => self::tableMx, "where" => " orderId = '$id' "]);
                    delete(["table" => "auditing_follow", "where" => " typeId = '$id' "]);
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 批量打印
     *
     * @return string
     */
    public function batchPrint(): string
    {
        $lists = $this->get('lists');
        if (empty($lists)) {
            exit('参数错误');
        } else {
            $listId = base64_decode($lists, true);
            $array  = explode(',', $listId);
            $data   = [];
            foreach ($array as $id) {
                $data[] = static::printPage($id, false);
            }
            return (new printTemplateClass())->start(self::page, $data);
        }
    }

    /**
     * 打印
     *
     * @return string
     */
    public function printPage($param = '', $isReturn = true): string|array
    {
        $id                  = $param ?: $this->get('id');
        $info                = query(self::table, " id = '$id'");
        $info['companyName'] = query('company', "coid = '" . self::$coid . "'")['name']; //公司名称//公司名称
        $info['title']       = self::title;
        $info['printTime']   = $this->time;
        $info['stid']        = self::findStaff($info['stid']);
        $info['checkId']     = '';
        $info['khName']      = query('kehu', "khid = '$info[khid]'")['companyName'];
        $info['qr']          = "source=" . self::table . "&id=" . $info['id'];
        $info['tags']        = orderTagClass::getTagName($info['id']);
        $detail              = find(['table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"])['array'];
        $items               = [];
        $x                   = 1;
        $totalNum            = 0;
        $totalMoney          = 0;
        foreach ($detail as $array) {
            $material  = query('material', "id = '$array[materialId]'");
            $warehouse = query('warehouse', "id = '$array[warehouseId]'");
            $items[]   = [
                'no'              => $x,
                'materialCode'    => $material['code'],
                'materialName'    => $material['name'],
                'warehouse'       => $warehouse['name'],
                'price'           => self::lostZero($array['price'], 'pricePrecision'),
                'rate'            => ($array['rate'] * 100) . '%',
                'taxMoney'        => self::lostZero($array['taxMoney'], 'amount'),
                'moneyWithOutTax' => self::formattingFigure($array['money'] - $array['taxMoney'], 'amount'),
                'money'           => self::lostZero($array['money'], 'amount'),
                'model'           => $material['model'],
                'unit'            => $array['unit'],
                'num'             => self::lostZero($array['num'], 'numPrecision'),
            ];
            $x++;
            $totalNum   += $array['num'];
            $totalMoney += $array['money'];
        }
        $append         = [
            'no'    => '合计',
            'num'   => self::lostZero($totalNum, 'amount'),
            'money' => self::lostZero($totalMoney, 'amount'),
        ];
        $items[]        = $append;
        $info['detail'] = $items;
        if ($isReturn) {
            return (new printTemplateClass())->start(self::page, $info);
        } else {
            return $info;
        }
    }
}

